<template>
  <view>
    <view class="top-switcher">
      <view
        v-for="(item, index) in mpages"
        :key="(item, index)"
        class="top-swicther-item"
        :class="currentSwiperIndex === index ? 'top-swicther-item-actived' : ''"
        @click="swiperChange(index)"
      >
        {{ item }}
      </view>
    </view>
    <swiper :current="currentSwiperIndex" @change="onSwiperChange">
      <swiper-item>
        <view class="page-title">用户名注册</view>
        <form @submit="signUpIdSubmit">
          <view class="input-grid">
            <view class="inline-text not-null">用户名</view>
            <input
              class="inline-text"
              type="text"
              name="userID"
              placeholder="一旦指定 不可更改"
            />
            <view class="inline-text not-null">密码</view>
            <input
              class="inline-text"
              type="password"
              name="password"
              placeholder="长度不小于6位"
            />
            <view class="inline-text not-null">确认密码</view>
            <input class="inline-text" type="password" name="confirmpw" />
          </view>
          <button form-type="submit" type="primary">注册</button>
        </form>
      </swiper-item>
      <swiper-item>
        <view class="page-title">用户名电话注册</view>
        <form @submit="signUpIdPhoneSubmit">
          <view class="input-grid">
            <view class="inline-text not-null">用户名</view>
            <input
              class="inline-text"
              type="text"
              name="userID"
              placeholder="一旦指定 不可更改"
            />
            <view class="inline-text">手机号</view>
            <input class="inline-text" type="text" name="phone" :value="phoneNumber"/>
            <view class="inline-text not-null">密码</view>
            <input
              class="inline-text"
              type="password"
              name="password"
              placeholder="长度不小于6位"
            />
            <view class="inline-text not-null">确认密码</view>
            <input class="inline-text" type="password" name="confirmpw" />
            <view class="inline-text">验证码</view>
            <view class="identify-code">
              <input class="inline-text" type="text" name="identiCode" />
              <button @click="sendIdentificationCode">发送验证码</button>
            </view>
          </view>
          <button form-type="submit" type="primary">注册</button>
        </form>
      </swiper-item>
    </swiper>
    <view v-html="response_data" class="response-data"></view>
  </view>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      response_data: "",
      mpages: ["用户名注册", "用户名+电话注册"],
      currentSwiperIndex: 0,
      phoneNumber: "",
    };
  },

  methods: {
    formatPostData: function (e) {
      let values = e.detail.value;
      if (!this.verifyNotNullInfo(values)) {
        return;
      }
      let postData = {
        userID: values.userID,
        password: password,
        option: "signUp",
      };
      if (values.phone) {
        postData.phone = values.phone;
      }
      return postData;
    },
    signUpIdSubmit: function (e) {
      uni.showLoading({ title: "加载中..." });
      let postData = this.formatPostData(e);
      postData.type = "authenticateByPassword";
      this.$http
        .post("/ShareYunAlbum/userServlet", postData)
        .then((res) => {
          uni.hideLoading();
          let status = res.data.status;
          switch (status) {
            case this.$responseCode.signUp.signUpSuccess: {
              console.log("注册成功");
              uni.showToast({ title: "注册成功!", icon: "success" });
              this.autoLoginAfterSignUp(userID, password);
              break;
            }
            case this.$responseCode.signUp.accountExistsError: {
              console.log("用户名已存在");
              uni.showToast({ title: "用户名已存在!", icon: "error" });
              break;
            }
            case this.$responseCode.signUp.unknownError: {
              console.log("未知错误");
              uni.showToast({ title: "未知错误!", icon: "error" });
              break;
            }
            default: {
              console.log(res);
              break;
            }
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({ title: "请求出错", icon: "error" });
          console.log(err);
        });
    },
    signUpIdPhoneSubmit: function (e) {
      uni.showLoading({ title: "加载中..." });
      let userID = e.detail.value.userID,
        phone = e.detail.value.phone,
        password = e.detail.value.password,
        confirmpw = e.detail.value.confirmpw,
        identiCode = e.detail.value.identiCode;
      if (!this.verifyNotNullInfo(e.detail.value)) {
        return;
      }
      let postdata = {
        option: "signUp",
        type: "authenticateByPassword",
        userID: userID,
        password: password,
      };
      if (phone != "") {
        postdata.phone = phone;
      }
      if (identiCode != "") {
        postdata.autuCode = identiCode;
      }
      // console.log(postdata);
      this.$http
        .post("/ShareYunAlbum/userServlet", postdata)
        .then((res) => {
          uni.hideLoading();
          let status = res.data.status;
          switch (status) {
            case this.$responseCode.signUp.signUpSuccess: {
              console.log("注册成功");
              uni.showToast({ title: "注册成功!", icon: "success" });
              this.autoLoginAfterSignUp(userID, password);
              break;
            }
            case this.$responseCode.signUp.accountExistsError: {
              console.log("用户名已存在");
              uni.showToast({ title: "用户名已存在!", icon: "error" });
              break;
            }
            case this.$responseCode.signUp.unknownError: {
              console.log("未知错误");
              uni.showToast({ title: "未知错误!", icon: "error" });
              break;
            }
            default: {
              console.log(res);
              break;
            }
          }
        })
        .catch((err) => {
          uni.hideLoading();
          console.log(err);
          uni.showToast({ title: "请求错误", icon: "error" });
        });
    },
    sendIdentificationCode: function () {
      let postData = {
        phone: this.phoneNumber,
        option: "signUp",
        type: "sendMessage"
      }


    },
    autoLoginAfterSignUp: function (userID, token) {
      uni.navigateBack();
      this.$http
        .post("/ShareYunAlbum/userServlet", {
          userID: userID,
          password: token,
          type: "authenticateByPassword",
          option: "signIn",
        })
        .then((response) => {
          let status = response.data.status;
          if (status == this.$responseCode.login.loginSuccess) {
            this.login({
              ...response.data,
              token: token,
            });
            uni.switchTab({ url: "/pages/mySpace/mySpace" });
          }
        })
        .catch((err) => {
          uni.showToast({ title: "发生错误", icon: "error" });
          console.log(err);
        });
    },
    verifyNotNullInfo: function (values) {
      if (
        values.userID == "" ||
        values.password == "" ||
        values.confirmpw == "" ||
        (values.phone && values.phone.length != 11) ||
        (values.identiCode && values.identiCode.length != 6)
      ) {
        uni.showToast({ title: "请填入有效的信息!", icon: "error" });
        return false;
      }
      if (values.password.length < 6) {
        uni.showToast({ title: "密码太短!", icon: "error" });
        return false;
      }
      if (values.password !== values.confirmpw) {
        uni.showToast({ title: "密码不一致!", icon: "error" });
        return false;
      }
      return true;
    },
    swiperChange: function (index) {
      this.currentSwiperIndex = index;
    },
    onSwiperChange: function (e) {
      this.currentSwiperIndex = e.detail.current;
    },
    ...mapMutations(["login"]),
  },
};
</script>

<style>
uni-swiper {
  height: 1000rpx;
}
.page-title {
  overflow: hidden;
  white-space: nowrap;
  font-size: 1.5em;
  text-align: center;
}
.input-grid {
  margin: 0 auto;
  display: grid;
  grid-template-columns: 25% 75%;
  /* grid-template-rows: 20% 20% 20% 20% 20%; */
  width: 90%;
}
.inline-text {
  font-size: 0.8em;
  padding: 5px;
  margin: 5px;
  overflow: hidden;
  white-space: nowrap;
}
uni-input {
  border: grey 1px solid;
  font-size: 1em;
  border-radius: 5px;
}
.identify-code {
  display: grid;
  grid-template-columns: 50% 50%;
}
.identify-code > button {
  width: 95%;
  overflow: hidden;
  white-space: nowrap;
}
.not-null::after {
  content: "*";
  color: red;
  font-size: 10rpx;
}
.top-swicther-item-actived {
  color: deepskyblue !important;
}
.top-swicther-item {
  font-size: 0.5em;
  margin: 20rpx;
  color: gray;
}
.top-switcher {
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
}
</style>